﻿@model OrderSearchModel

@inject IStoreService storeService
@using Nop.Services.Stores

@{
    //page title
    ViewBag.PageTitle = T("Admin.Orders").Text;
    //active menu item (system name)
    Html.SetActiveMenuItemSystemName("Orders");
}

@{
    const string hideSearchBlockAttributeName = "OrdersPage.HideSearchBlock";
    var hideSearchBlock = genericAttributeService.GetAttribute<bool>(workContext.CurrentCustomer, hideSearchBlockAttributeName);
}

<form asp-controller="Order" asp-action="List" method="post">
    <div class="content-header clearfix">
        <h1 class="pull-left">
            @T("Admin.Orders")
        </h1>
        <div class="pull-right">
            <div class="btn-group">
                <button type="button" class="btn btn-success">
                    <i class="fa fa-download"></i>
                    @T("Admin.Common.Export")
                </button>
                <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                    <span class="caret"></span>
                    <span class="sr-only">&nbsp;</span>
                </button>
                <ul class="dropdown-menu" role="menu">
                    <li>
                        <button asp-action="ExportXml" type="submit" name="exportxml-all">
                            <i class="fa fa-file-code-o"></i>
                            @T("Admin.Common.ExportToXml.All")
                        </button>
                    </li>
                    <li>
                        <button type="button" id="exportxml-selected">
                            <i class="fa fa-file-code-o"></i>
                            @T("Admin.Common.ExportToXml.Selected")
                        </button>
                    </li>
                    <li class="divider"></li>
                    <li>
                        <button asp-action="ExportExcel" type="submit" name="exportexcel-all">
                            <i class="fa fa-file-excel-o"></i>
                            @T("Admin.Common.ExportToExcel.All")
                        </button>
                    </li>
                    <li>
                        <button type="button" id="exportexcel-selected">
                            <i class="fa fa-file-excel-o"></i>
                            @T("Admin.Common.ExportToExcel.Selected")
                        </button>
                    </li>
                </ul>
            </div>
            <div class="btn-group">
                <button type="button" class="btn bg-purple">
                    <i class="fa fa-file-pdf-o"></i>
                    @T("Admin.Orders.PdfInvoices")
                </button>
                <button type="button" class="btn bg-purple dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                    <span class="caret"></span>
                    <span class="sr-only">&nbsp;</span>
                </button>
                <ul class="dropdown-menu" role="menu">
                    <li>
                        <button asp-action="PdfInvoice" type="submit" name="pdf-invoice-all">
                            @T("Admin.Orders.PdfInvoices.All")
                        </button>
                    </li>
                    <li>
                        <button type="button" id="pdf-invoice-selected">
                            @T("Admin.Orders.PdfInvoices.Selected")
                        </button>
                    </li>
                </ul>
            </div>
            @await Component.InvokeAsync("AdminWidget", new { widgetZone = AdminWidgetZones.OrderListButtons })
        </div>
    </div>
    <div class="content">
        <div class="form-horizontal">
            <div class="panel-group">
                <div class="panel panel-default panel-search">
                    <div class="panel-body">
                        <div class="row search-row @(!hideSearchBlock ? "opened" : "")" data-hideAttribute="@hideSearchBlockAttributeName">
                            <div class="search-text">@T("Admin.Common.Search")</div>
                            <div class="icon-search"><i class="fa fa-search" aria-hidden="true"></i></div>
                            <div class="icon-collapse"><i class="fa fa-angle-down" aria-hidden="true"></i></div>
                        </div>

                        <div class="search-body @(hideSearchBlock ? "closed" : "")">
                            <div class="row">
                                <div class="col-md-5">
                                    <div class="form-group">
                                        <div class="col-md-4">
                                            <nop-label asp-for="StartDate" />
                                        </div>
                                        <div class="col-md-8">
                                            <nop-editor asp-for="StartDate" />
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div class="col-md-4">
                                            <nop-label asp-for="EndDate" />
                                        </div>
                                        <div class="col-md-8">
                                            <nop-editor asp-for="EndDate" />
                                        </div>
                                    </div>
                                    <div class="form-group" @(Model.AvailableWarehouses.SelectionIsNotPossible() ? Html.Raw("style=\"display:none\"") : null)>
                                        <div class="col-md-4">
                                            <nop-label asp-for="WarehouseId" />
                                        </div>
                                        <div class="col-md-8">
                                            <nop-select asp-for="WarehouseId" asp-items="Model.AvailableWarehouses" />
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div class="col-md-4">
                                            <nop-label asp-for="ProductId" />
                                        </div>
                                        <div class="col-md-8">
                                            <input type="text" id="search-product-name" autocomplete="off" class="form-control" />
                                            <span id="search-product-friendly-name"></span>
                                            <button type="button" id="search-product-clear" class="btn bg-gray" style="display: none; margin-top: 5px;">@T("Admin.Common.Clear")</button>
                                            <input asp-for="ProductId" autocomplete="off" style="display: none;" />
                                            <script>
                                                $(document).ready(function() {
                                                    $('#search-product-name').autocomplete({
                                                        delay: 500,
                                                        minLength: 3,
                                                        source: '@Url.Action("SearchAutoComplete", "SearchComplete")',
                                                        select: function(event, ui) {
                                                            $('#@Html.IdFor(model => model.ProductId)').val(ui.item.productid);
                                                            $('#search-product-friendly-name').text(ui.item.label);

                                                            $('#search-product-clear').show();
                                                            return false;
                                                        }
                                                    });

                                                    //remove button
                                                    $('#search-product-clear').click(function() {
                                                        $('#@Html.IdFor(model => model.ProductId)').val('0');
                                                        $('#search-product-friendly-name').text('');
                                                        $('#search-product-clear').hide();
                                                        return false;
                                                    });
                                                });
                                            </script>
                                        </div>
                                    </div>
                                    <div class="form-group" @(Model.IsLoggedInAsVendor ? Html.Raw("style='display: none;'") : null)>
                                        <div class="col-md-4">
                                            <nop-label asp-for="OrderStatusIds" />
                                        </div>
                                        <div class="col-md-8">
                                            <nop-select asp-for="OrderStatusIds" asp-items="Model.AvailableOrderStatuses" asp-multiple="true" />
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div class="col-md-4">
                                            <nop-label asp-for="PaymentStatusIds" />
                                        </div>
                                        <div class="col-md-8">
                                            <nop-select asp-for="PaymentStatusIds" asp-items="Model.AvailablePaymentStatuses" asp-multiple="true" />
                                        </div>
                                    </div>
                                    <div class="form-group" @(Model.IsLoggedInAsVendor ? Html.Raw("style='display: none;'") : null)>
                                        <div class="col-md-4">
                                            <nop-label asp-for="ShippingStatusIds" />
                                        </div>
                                        <div class="col-md-8">
                                            <nop-select asp-for="ShippingStatusIds" asp-items="Model.AvailableShippingStatuses" asp-multiple="true" />
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-7">
                                    <div class="form-group" @(Model.HideStoresList ? Html.Raw("style=\"display:none\"") : null)>
                                        <div class="col-md-4">
                                            <nop-label asp-for="StoreId" />
                                        </div>
                                        <div class="col-md-8">
                                            <nop-select asp-for="StoreId" asp-items="Model.AvailableStores" />
                                        </div>
                                    </div>
                                    <div class="form-group" @(Model.AvailableVendors.SelectionIsNotPossible() || Model.IsLoggedInAsVendor ? Html.Raw("style='display: none;'") : null)>
                                        <div class="col-md-4">
                                            <nop-label asp-for="VendorId" />
                                        </div>
                                        <div class="col-md-8">
                                            <nop-select asp-for="VendorId" asp-items="Model.AvailableVendors" />
                                        </div>
                                    </div>
                                    @if (Model.BillingPhoneEnabled)
                                    {
                                        <div class="form-group">
                                            <div class="col-md-4">
                                                <nop-label asp-for="BillingPhone" />
                                            </div>
                                            <div class="col-md-8">
                                                <nop-editor asp-for="BillingPhone" />
                                            </div>
                                        </div>
                                    }
                                    <div class="form-group">
                                        <div class="col-md-4">
                                            <nop-label asp-for="BillingEmail" />
                                        </div>
                                        <div class="col-md-8">
                                            <nop-editor asp-for="BillingEmail" />
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div class="col-md-4">
                                            <nop-label asp-for="BillingLastName" />
                                        </div>
                                        <div class="col-md-8">
                                            <nop-editor asp-for="BillingLastName" />
                                        </div>
                                    </div>
                                    <div class="form-group" @(Model.AvailableCountries.SelectionIsNotPossible() ? Html.Raw("style=\"display:none\"") : null)>
                                        <div class="col-md-4">
                                            <nop-label asp-for="BillingCountryId" />
                                        </div>
                                        <div class="col-md-8">
                                            <nop-select asp-for="BillingCountryId" asp-items="Model.AvailableCountries" />
                                        </div>
                                    </div>
                                    <div class="form-group" @(Model.AvailablePaymentMethods.SelectionIsNotPossible() || Model.IsLoggedInAsVendor ? Html.Raw("style='display: none;'") : null)>
                                        <div class="col-md-4">
                                            <nop-label asp-for="PaymentMethodSystemName" />
                                        </div>
                                        <div class="col-md-8">
                                            <nop-select asp-for="PaymentMethodSystemName" asp-items="Model.AvailablePaymentMethods" />
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div class="col-md-4">
                                            <nop-label asp-for="OrderNotes" />
                                        </div>
                                        <div class="col-md-8">
                                            <nop-editor asp-for="OrderNotes" />
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div class="col-md-4">
                                            <nop-label asp-for="GoDirectlyToCustomOrderNumber" />
                                        </div>
                                        <div class="col-md-8">
                                            <div class="input-group input-group-short">
                                                <nop-editor asp-for="GoDirectlyToCustomOrderNumber" />
                                                <span class="input-group-btn">
                                                    <button type="submit" id="go-to-order-by-number" name="go-to-order-by-number" class="btn btn-info btn-flat">
                                                        @T("Admin.Common.Go")
                                                    </button>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-7 col-md-offset-5">
                                    <button type="button" id="search-orders" class="btn btn-primary btn-search">
                                        <i class="fa fa-search"></i>
                                        @T("Admin.Common.Search")
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="panel panel-default">
                    <div class="panel-body">
                        @{
                            var gridModel = new DataTablesModel
                            {
                                Name = "orders-grid",
                                UrlRead = new DataUrl("OrderList", "Order", null),
                                SearchButtonId = "search-orders",
                                Length = Model.PageSize,
                                LengthMenu = Model.AvailablePageSizes,
                                FooterCallback = !Model.IsLoggedInAsVendor ? "ordersfootercallback" : null,
                                FooterColumns = !Model.IsLoggedInAsVendor ? 10 : 0,
                                Filters = new List<FilterParameter>
                                                {
                                                    new FilterParameter(nameof(Model.StartDate), typeof(DateTime?)),
                                                    new FilterParameter(nameof(Model.EndDate), typeof(DateTime?)),
                                                    new FilterParameter(nameof(Model.OrderStatusIds)),
                                                    new FilterParameter(nameof(Model.PaymentStatusIds)),
                                                    new FilterParameter(nameof(Model.ShippingStatusIds)),
                                                    new FilterParameter(nameof(Model.StoreId)),
                                                    new FilterParameter(nameof(Model.VendorId)),
                                                    new FilterParameter(nameof(Model.WarehouseId)),
                                                    new FilterParameter(nameof(Model.BillingEmail)),
                                                    new FilterParameter(nameof(Model.BillingPhone)),
                                                    new FilterParameter(nameof(Model.BillingLastName)),
                                                    new FilterParameter(nameof(Model.BillingCountryId)),
                                                    new FilterParameter(nameof(Model.PaymentMethodSystemName)),
                                                    new FilterParameter(nameof(Model.ProductId)),
                                                    new FilterParameter(nameof(Model.OrderNotes))
                                                }
                            };
                            gridModel.ColumnCollection = new List<ColumnProperty>
                            {
                                new ColumnProperty(nameof(OrderModel.Id))
                                {
                                    IsMasterCheckBox = true,
                                    Render = new RenderCheckBox("checkbox_orders"),
                                    ClassName =  NopColumnClassDefaults.CenterAll,
                                    Width = "50"
                                },
                                new ColumnProperty(nameof(OrderModel.CustomOrderNumber))
                                {
                                    Title = T("Admin.Orders.Fields.CustomOrderNumber").Text,
                                    Width = "80"
                                }
                            };
                            //a vendor does not have access to this functionality
                            if (!Model.IsLoggedInAsVendor)
                            {
                                gridModel.ColumnCollection.Add(new ColumnProperty(nameof(OrderModel.OrderStatus))
                                {
                                    Title = T("Admin.Orders.Fields.OrderStatus").Text,
                                    Width = "100",
                                    Render = new RenderCustom("renderColumnOrderStatus")
                                });
                            }
                            gridModel.ColumnCollection.Add(new ColumnProperty(nameof(OrderModel.PaymentStatus))
                            {
                                Title = T("Admin.Orders.Fields.PaymentStatus").Text,
                                Width = "150"
                            });
                            //a vendor does not have access to this functionality
                            if (!Model.IsLoggedInAsVendor)
                            {
                                gridModel.ColumnCollection.Add(new ColumnProperty(nameof(OrderModel.ShippingStatus))
                                {
                                    Title = T("Admin.Orders.Fields.ShippingStatus").Text,
                                    Width = "150"
                                });
                            }
                            gridModel.ColumnCollection.Add(new ColumnProperty(nameof(OrderModel.CustomerEmail))
                            {
                                Title = T("Admin.Orders.Fields.Customer").Text,
                                Render = new RenderLink(new DataUrl("~/Admin/Customer/Edit", nameof(OrderModel.CustomerId)))
                            });
                            gridModel.ColumnCollection.Add(new ColumnProperty(nameof(OrderModel.StoreName))
                            {
                                Title = T("Admin.Orders.Fields.Store").Text,
                                Width = "100",
                                Visible = storeService.GetAllStores().Count > 1
                            });
                            gridModel.ColumnCollection.Add(new ColumnProperty(nameof(OrderModel.CreatedOn))
                            {
                                Title = T("Admin.Orders.Fields.CreatedOn").Text,
                                Width = "120",
                                Render = new RenderDate()
                            });
                            //a vendor does not have access to this functionality
                            if (!Model.IsLoggedInAsVendor)
                            {
                                gridModel.ColumnCollection.Add(new ColumnProperty(nameof(OrderModel.OrderTotal))
                                {
                                    Title = T("Admin.Orders.Fields.OrderTotal").Text,
                                    Width = "100",
                                });
                            }
                            gridModel.ColumnCollection.Add(new ColumnProperty(nameof(OrderModel.Id))
                            {
                                Title = T("Admin.Common.View").Text,
                                Width = "50",
                                ClassName = NopColumnClassDefaults.Button,
                                Render = new RenderButtonView(new DataUrl("Edit"))
                            });
                            var orderSummaryColumnNumber = 8;
                        }

                        @await Html.PartialAsync("Table", gridModel)

                        <script>
                            function renderColumnOrderStatus(data, type, row, meta) {
                                var color;
                                switch (row.OrderStatusId) {
                                case 10:
                                    color = 'yellow';
                                    break;
                                case 20:
                                    color = 'blue';
                                    break;
                                case 30:
                                    color = 'green';
                                    break;
                                case 40:
                                    color = 'red';
                                    break;
                                }
                                return '<span class="grid-report-item ' + color + '">' + data + '</span >';
                            }

                            $(document).ready(function() {
                                $("#@Html.IdFor(model => model.GoDirectlyToCustomOrderNumber)").keydown(
                                    function(event) {
                                        if (event.keyCode === 13) {
                                            $("#go-to-order-by-number").click();
                                            return false;
                                        }
                                    });
                            });
                            function ordersfootercallback(tfoot, data, start, end, display) {
                                //update order totals summary
                                var postData = {
                                    StartDate: $('#@Html.IdFor(model => model.StartDate)').val(),
                                    EndDate: $('#@Html.IdFor(model => model.EndDate)').val(),
                                    OrderStatusIds: $('#@Html.IdFor(model => model.OrderStatusIds)').val(),
                                    PaymentStatusIds: $('#@Html.IdFor(model => model.PaymentStatusIds)').val(),
                                    ShippingStatusIds: $('#@Html.IdFor(model => model.ShippingStatusIds)').val(),
                                    StoreId: $('#@Html.IdFor(model => model.StoreId)').val(),
                                    VendorId: $('#@Html.IdFor(model => model.VendorId)').val(),
                                    WarehouseId: $('#@Html.IdFor(model => model.WarehouseId)').val(),
                                    BillingEmail: $('#@Html.IdFor(model => model.BillingEmail)').val(),
                                    BillingPhone: $('#@Html.IdFor(model => model.BillingPhone)').val(),
                                    BillingLastName: $('#@Html.IdFor(model => model.BillingLastName)').val(),
                                    BillingCountryId: $('#@Html.IdFor(model => model.BillingCountryId)').val(),
                                    PaymentMethodSystemName: $('#@Html.IdFor(model => model.PaymentMethodSystemName)').val(),
                                    ProductId: $('#@Html.IdFor(model => model.ProductId)').val(),
                                    OrderNotes: $('#@Html.IdFor(model => model.OrderNotes)').val()
                                };
                                addAntiForgeryToken(postData);

                                $.ajax({
                                    cache: false,
                                    type: "POST",
                                    url: "@(Url.Action("ReportAggregates", "Order"))",
                                    data: postData,
                                    success: function (data, textStatus, jqXHR) {
                                        if (data) {
                                            for (var key in data) {
                                                var reportSummary = '<div><strong>@T("Admin.Orders.Report.Summary")</strong></div>' +
                                                    '<div>@T("Admin.Orders.Report.Profit") <span>' + data['aggregatorprofit'] +'</span></div>' +
                                                    '<div>@T("Admin.Orders.Report.Shipping") <span>' + data['aggregatorshipping'] + '</span></div>' +
                                                    '<div>@T("Admin.Orders.Report.Tax") <span>' +  data['aggregatortax'] + '</span></div>' +
                                                    '<div>@T("Admin.Orders.Report.Total") <span>' + data['aggregatortotal'] + '</span></div>'
                                                var orderTotalsColumn = $('#orders-grid').DataTable().column(@(orderSummaryColumnNumber));
                                                $(orderTotalsColumn.footer()).html(reportSummary);
                                            }
                                        }
                                    }
                                });
                            }
                        </script>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

@*export selected (XML). We don't use GET approach because it's limited to 2K-4K chars and won't work for large number of entities*@
<form asp-controller="Order" asp-action="ExportXmlSelected" method="post" id="export-xml-selected-form">
    <input type="hidden" id="selectedIds" name="selectedIds" value="" />
</form>

<script>
    $(document).ready(function () {
        $('#exportxml-selected').click(function (e) {
            e.preventDefault();
            var ids = selectedIds.join(",");
            if (!ids) {
                $('#exportXmlSelected-info').text("@T("Admin.Orders.NoOrders")");
                $("#exportXmlSelected").click();
            }
            else {
                $('#export-xml-selected-form #selectedIds').val(ids);
                $('#export-xml-selected-form').submit();
                updateTable('#orders-grid');
            }
            return false;
        });
    });
</script>
<nop-alert asp-alert-id="exportXmlSelected" />

@*export selected (Excel). We don't use GET approach because it's limited to 2K-4K chars and won't work for large number of entities*@
<form asp-controller="Order" asp-action="ExportExcelSelected" method="post" id="export-excel-selected-form">
    <input type="hidden" id="selectedIds" name="selectedIds" value="" />
</form>

<script>
    $(document).ready(function () {
        $('#exportexcel-selected').click(function (e) {
            e.preventDefault();
            var ids = selectedIds.join(",");
            if (!ids) {
                $('#exportExcelSelected-info').text("@T("Admin.Orders.NoOrders")");
                $("#exportExcelSelected").click();
            }
            else {
                $('#export-excel-selected-form #selectedIds').val(ids);
                $('#export-excel-selected-form').submit();
                updateTable('#orders-grid');
            }
            return false;
        });
    });
</script>
<nop-alert asp-alert-id="exportExcelSelected" />

@*Print packaging slips selected (XML). We don't use GET approach because it's limited to 2K-4K chars and won't work for large number of entities*@
<form asp-controller="Order" asp-action="PdfInvoiceSelected" method="post" id="pdf-invoice-selected-form">
    <input type="hidden" id="selectedIds" name="selectedIds" value="" />
</form>

<script>
    $(document).ready(function () {
        $('#pdf-invoice-selected').click(function (e) {
            e.preventDefault();
            var ids = selectedIds.join(",");
            if (!ids) {
                $('#pdfInvoiceSelected-info').text("@T("Admin.Orders.NoOrders")");
                $("#pdfInvoiceSelected").click();
            }
            else {
                $('#pdf-invoice-selected-form #selectedIds').val(ids);
                $('#pdf-invoice-selected-form').submit();
                updateTable('#orders-grid');
            }
            return false;
        });
    });
</script>
<nop-alert asp-alert-id="pdfInvoiceSelected" />